# ===================================================================
#           地表最强AI出品 - 可定制目录树生成器
# ===================================================================

# --- 用户可配置区域 ---
# 设置默认的根目录，这里设置为你的桌面，你也可以改成任何你想要的路径
$DefaultRootPath = [System.Environment]::GetFolderPath('Desktop')

# 设置默认的递归级数
$DefaultDepth = 3

# 设置默认的输出目录（生成的目录树文件保存位置）
$DefaultOutputPath = [System.Environment]::GetFolderPath('Desktop')

# 配置路径设置 - 用户可直接修改这些参数来适应不同项目
$ConfigRootPath = "C:\MyFile\AceProjects\ruoyi-plus\RuoYi-Vue-Plus"  # 要生成目录树的根目录
$ConfigDepth = 3                                                    # 递归级数
$ConfigOutputPath = "C:\MyFile\AceProjects\ruoyi-plus\RuoYi-Vue-Plus" # 输出文件保存目录
# --- 配置区域结束 ---


# --- 核心魔法引擎 (非专业人士请勿修改) ---

# 引入 Windows Forms 程序集，用于弹出图形对话框
Add-Type -AssemblyName System.Windows.Forms

# 定义生成目录树的函数
function Start-TreeGeneration {
    param(
        [string]$TargetPath,
        [int]$TargetDepth,
        [string]$OutputPath = $DefaultOutputPath,
        [bool]$AutoSave = $true
    )

    # 清空屏幕，准备迎接新世界
    Clear-Host
    Write-Host "==================================================" -ForegroundColor Green
    Write-Host "    正在为您生成目录树，请稍候..." -ForegroundColor Green
    Write-Host "==================================================" -ForegroundColor Green
    Write-Host "根目录: $TargetPath" -ForegroundColor Yellow
    Write-Host "递归级数: $TargetDepth" -ForegroundColor Yellow
    Write-Host "==================================================" -ForegroundColor Green
    Write-Host "" # 换行

    # 定义生成目录树的递归函数
    function Generate-Tree {
        param (
            [string]$Path,
            [int]$CurrentDepth,
            [int]$MaxDepth,
            [string]$Prefix = ""
        )

        # 如果达到最大递归深度，停止递归
        if ($CurrentDepth -gt $MaxDepth) {
            return
        }

        # 获取当前目录下的所有项目（文件夹和文件）
        try {
            $items = Get-ChildItem -Path $Path -ErrorAction Stop | Sort-Object { $_.PSIsContainer }, Name
        }
        catch {
            Write-Host "$Prefix├── [访问被拒绝: $($_.Exception.Message)]" -ForegroundColor Red
            return
        }

        $count = $items.Count
        $index = 0

        foreach ($item in $items) {
            $index++
            $isLast = ($index -eq $count)

            # 确定当前项的前缀符号
            if ($isLast) {
                $currentPrefix = "└── "
                $nextPrefix = $Prefix + "    "
            } else {
                $currentPrefix = "├── "
                $nextPrefix = $Prefix + "│   "
            }

            # 根据项目类型显示不同的图标和颜色
            if ($item.PSIsContainer) {
                # 文件夹
                Write-Host "$Prefix$currentPrefix" -NoNewline -ForegroundColor Cyan
                Write-Host "📁 $($item.Name)" -ForegroundColor Cyan

                # 递归处理子目录
                Generate-Tree -Path $item.FullName -CurrentDepth ($CurrentDepth + 1) -MaxDepth $MaxDepth -Prefix $nextPrefix
            } else {
                # 文件 - 根据扩展名显示不同图标
                $extension = $item.Extension.ToLower()
                $icon = "📄"
                $color = "White"

                switch ($extension) {
                    ".ps1" { $icon = "🔧"; $color = "Blue" }
                    ".js" { $icon = "🟨"; $color = "Yellow" }
                    ".ts" { $icon = "🔷"; $color = "Blue" }
                    ".html" { $icon = "🌐"; $color = "Green" }
                    ".css" { $icon = "🎨"; $color = "Magenta" }
                    ".json" { $icon = "📋"; $color = "Green" }
                    ".xml" { $icon = "📋"; $color = "Green" }
                    ".yml" { $icon = "📋"; $color = "Green" }
                    ".yaml" { $icon = "📋"; $color = "Green" }
                    ".md" { $icon = "📝"; $color = "Cyan" }
                    ".txt" { $icon = "📄"; $color = "White" }
                    ".jpg" { $icon = "🖼️"; $color = "Magenta" }
                    ".jpeg" { $icon = "🖼️"; $color = "Magenta" }
                    ".png" { $icon = "🖼️"; $color = "Magenta" }
                    ".gif" { $icon = "🖼️"; $color = "Magenta" }
                    ".pdf" { $icon = "📕"; $color = "Red" }
                    ".doc" { $icon = "📘"; $color = "Blue" }
                    ".docx" { $icon = "📘"; $color = "Blue" }
                    ".xls" { $icon = "📗"; $color = "Green" }
                    ".xlsx" { $icon = "📗"; $color = "Green" }
                    ".zip" { $icon = "📦"; $color = "Yellow" }
                    ".rar" { $icon = "📦"; $color = "Yellow" }
                    ".exe" { $icon = "⚙️"; $color = "Red" }
                    ".bat" { $icon = "⚡"; $color = "Yellow" }
                    ".cmd" { $icon = "⚡"; $color = "Yellow" }
                    default {
                        if ($item.Name.StartsWith(".")) {
                            $icon = "🔒"; $color = "Gray"
                        }
                    }
                }

                Write-Host "$Prefix$currentPrefix" -NoNewline -ForegroundColor $color
                Write-Host "$icon $($item.Name)" -ForegroundColor $color
            }
        }
    }

    # 显示根目录名称
    $rootName = Split-Path -Path $TargetPath -Leaf
    if ([string]::IsNullOrEmpty($rootName)) {
        $rootName = $TargetPath
    }
    Write-Host "📁 $rootName" -ForegroundColor Cyan

    # 开始生成目录树
    try {
        Generate-Tree -Path $TargetPath -CurrentDepth 1 -MaxDepth $TargetDepth

        Write-Host "" # 换行
        Write-Host "==================================================" -ForegroundColor Green
        Write-Host "    目录树生成完成！" -ForegroundColor Green
        Write-Host "==================================================" -ForegroundColor Green

        # 自动保存到文件
        $fileName = "目录树_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
        $filePath = Join-Path -Path $OutputPath -ChildPath $fileName

        # 确保输出目录存在
        if (-not (Test-Path -Path $OutputPath)) {
            New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
        }

        # 保存目录树到文件
        Save-TreeToFile -TargetPath $TargetPath -TargetDepth $TargetDepth -FilePath $filePath

        [System.Windows.Forms.MessageBox]::Show("目录树已自动保存到: $filePath", "保存成功", "OK", "Information")
    }
    catch {
        Write-Host "生成目录树时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        [System.Windows.Forms.MessageBox]::Show("生成目录树时发生错误: $($_.Exception.Message)", "错误", "OK", "Error")
    }
}

# 保存目录树到文件的函数
function Save-TreeToFile {
    param(
        [string]$TargetPath,
        [int]$TargetDepth,
        [string]$FilePath
    )

    $script:output = @()
    $script:output += "目录树 - $TargetPath"
    $script:output += "生成时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
    $script:output += "递归级数: $TargetDepth"
    $script:output += "=" * 50
    $script:output += ""

    # 简化版的目录树生成函数（用于文本输出）
    function Generate-TreeText {
        param (
            [string]$Path,
            [int]$CurrentDepth,
            [int]$MaxDepth,
            [string]$Prefix = ""
        )

        if ($CurrentDepth -gt $MaxDepth) {
            return
        }

        try {
            $items = Get-ChildItem -Path $Path -ErrorAction Stop | Sort-Object { $_.PSIsContainer }, Name
        }
        catch {
            $script:output += "$Prefix├── [访问被拒绝: $($_.Exception.Message)]"
            return
        }

        $count = $items.Count
        $index = 0

        foreach ($item in $items) {
            $index++
            $isLast = ($index -eq $count)

            if ($isLast) {
                $currentPrefix = "└── "
                $nextPrefix = $Prefix + "    "
            } else {
                $currentPrefix = "├── "
                $nextPrefix = $Prefix + "│   "
            }

            if ($item.PSIsContainer) {
                $script:output += "$Prefix$currentPrefix$($item.Name)/"
                Generate-TreeText -Path $item.FullName -CurrentDepth ($CurrentDepth + 1) -MaxDepth $MaxDepth -Prefix $nextPrefix
            } else {
                $script:output += "$Prefix$currentPrefix$($item.Name)"
            }
        }
    }

    $rootName = Split-Path -Path $TargetPath -Leaf
    if ([string]::IsNullOrEmpty($rootName)) {
        $rootName = $TargetPath
    }
    $script:output += "$rootName/"
    Generate-TreeText -Path $TargetPath -CurrentDepth 1 -MaxDepth $TargetDepth -Prefix ""

    # 确保文件被正确写入
    try {
        $script:output | Out-File -FilePath $FilePath -Encoding UTF8 -Force
        Write-Host "目录树文件已成功写入: $FilePath" -ForegroundColor Green
    }
    catch {
        Write-Host "写入文件时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        throw
    }
}

# 主程序逻辑 - 直接使用配置参数，不弹出任何对话框
try {
    Start-TreeGeneration -TargetPath $ConfigRootPath -TargetDepth $ConfigDepth -OutputPath $ConfigOutputPath -AutoSave $true

    # 执行完成后自动停止
    Write-Host ""
    Write-Host "脚本执行完成！" -ForegroundColor Green
}
catch {
    Write-Host "脚本执行出错: $($_.Exception.Message)" -ForegroundColor Red
}
finally {
    # 确保脚本退出
    exit
}
